﻿
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports S7.Net
Module IMCO_public
    Public plc As Plc 'PLC连接
    '生产线socket通讯，网络状态标识
    Public imsocket_status As String 'socket 通讯状态
    Public imsocket_lasttime As DateTime = Now '上次socket 通讯时间

    '将16进制转化为10进制
    Function ConvertHexToInt(str As String)
        Dim strresult As Integer
        strresult = CInt(Val("&H" & str))

        '      Return Convert.ToInt32(str, 16)
        Return strresult


    End Function
    '将10进制转化为16进制
    Function ConvertIntToHex(str As Integer)
        Return Hex(str)
    End Function
    '二进制转换为16进制,用于将接收到的二进制数据转化为十六进制数

    Public Function ConvertBytesToHex(arrByte As Byte(), reverse As Boolean) As String

        Dim sb As New StringBuilder
        'If (reverse) Then
        '    Array.Reverse(arrByte)
        'End If
        For Each b As Byte In arrByte
            Convert.ToInt16(b) '字符转化为十进制
            sb.AppendFormat(" {0:x2}", b) 'String.Format("{0:x}", int) 将十进制的转化为16进制的数据
        Next
        Dim content As String = sb.ToString().ToUpper
        'For i = content.Length To 1 Step -1
        '    If Mid(content, i, 1) <> "0" Then
        '        content = Mid(content, 1, i)
        '        Exit For
        '    End If
        'Next
        Return content
    End Function
    '将16进制转化为2进制，注意中间间隔的空格
    Function ConvertHexToBytes(str As String) As Byte()

        Dim TestArray() As String = Split(str) '将16进制数拆分为数组
        Dim hexBytes() As Byte
        ReDim hexBytes(TestArray.Length - 1)
        Dim i As Integer
        For i = 0 To TestArray.Length - 1
            hexBytes(i) = Val("&h" & TestArray(i)) '将16进制数转化为2进制
        Next
        Return hexBytes
    End Function

    'S7系列读取
    Function readS7plc(plcmodel As String, plcip As String, plcjijia As String, plcchacao As String, dbnum As String, dbblocktype As DataType, dbdatatype As String, dbdataaddress As String, dbweinum As String)

        Dim connectstr As String = "connect success"
        If Not plc.IsConnected Then
            connectstr = IMSocketTest.Remoteconnectplc(plcmodel, plcip, plcjijia, plcchacao)

        End If
        If connectstr = "connect success" Then
            Dim readstr As String

            readstr = IMSocketTest.readdata(dbnum, dbblocktype, dbdatatype, dbdataaddress, dbweinum)

            '     IMCO_SocketPLC.breakconnect()

            Return readstr
        Else
            Return (connectstr)
        End If
    End Function

End Module
